<?php

class SJB_Admin_Classifieds_ListingActions extends SJB_Function
{
	public function isAccessible()
	{
		$this->setPermissionLabel('manage_listings');
		return parent::isAccessible();
	}

	public function execute()
	{
		$restore = 'restore=';

		if (isset($_REQUEST['action_name'], $_REQUEST['listings'])) {
			$listings_ids = $_REQUEST['listings'];

			switch (strtolower($_REQUEST['action_name'])) {
				case 'activate':
					foreach ($listings_ids as $listing_id => $value) {
						SJB_ListingManager::activateListingBySID($listing_id);
						$listing = SJB_ListingManager::getObjectBySID($listing_id);
						if (SJB_UserNotificationsManager::isUserNotifiedOnListingActivation($listing->getUserSID())) {
							SJB_Notifications::sendUserListingActivatedLetter($listing, $listing->getUserSID());
						}
					}
					break;

				case 'deactivate':
					foreach ($listings_ids as $listing_id => $value) {
						SJB_ListingManager::deactivateListingBySID($listing_id);
					}
					break;

				case 'delete':
					foreach ($listings_ids as $listing_id => $value) {
						SJB_ListingManager::deleteListingBySID($listing_id);
					}
					break;

				case 'datemodify':
					if (isset($_REQUEST['date_to_change'])) {
						$dateToUpdate = $_REQUEST['date_to_change'];
						$date = SJB_I18N::getInstance()->getInput('date', $dateToUpdate);
						foreach ($listings_ids as $listing_id => $value) {
							$listingInfo = SJB_ListingManager::getListingInfoBySID($listing_id);
							$result = SJB_DB::query('UPDATE `listings` SET `expiration_date` = ?s WHERE `sid` = ?n', $date, $listingInfo['sid']);
						}
					}
					break;

				case 'approve':
					foreach ($listings_ids as $listing_id => $value) {
						SJB_ListingManager::setListingApprovalStatus($listing_id, 'approved');
						$user_sid = SJB_ListingManager::getUserSIDByListingSID($listing_id);
						if (SJB_UserNotificationsManager::isUserNotifiedOnListingApprove($user_sid)) {
							SJB_Notifications::sendUserListingApproveOrRejectLetter($listing_id, $user_sid, 'approve');
						}
					}
					break;

				case 'reject':
					foreach ($listings_ids as $listing_id => $value) {
						$res = SJB_ListingManager::setListingApprovalStatus($listing_id, 'rejected');
						$user_sid = SJB_ListingManager::getUserSIDByListingSID($listing_id);
						if (SJB_UserNotificationsManager::isUserNotifiedOnListingReject($user_sid))
							SJB_Notifications::sendUserListingApproveOrRejectLetter($listing_id, $user_sid, 'reject');
					}
					break;

				default:
					$restore = '';
					break;
			}
		}

		SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/manage-listings/?action=search&' . $restore);
	}
}